import axios from "axios";
import { serialize } from "@/util/util";
import NProgress from "nprogress"; // progress bar
import errorCode from "@/const/errorCode";
import { Message, MessageBox } from "element-ui";
import "nprogress/nprogress.css";
import qs from "qs";
import store from "@/store"; // progress bar style
axios.defaults.timeout = 30000;
var countDown = 10;

// 返回其他状态吗
axios.defaults.validateStatus = function(status) {
  return status >= 200 && status <= 500; // 默认的
};
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
  showSpinner: false
});

// HTTPrequest拦截
axios.interceptors.request.use(
  config => {
    NProgress.start(); // start progress bar
    const isToken = (config.headers || {}).isToken === false;
    let token = store.getters.access_token;
    if (token && !isToken) {
      config.headers["Authorization"] = "Bearer " + token; // token
    }

    let appId = store.getters.setAppId;
    if (appId) {
      config.headers["app-id"] = appId; // 应用id
    }else {
      config.headers["app-id"] = store.getters.website.appId;
    }
    // headers中配置serialize为true开启序列化
    if (config.methods === "post" && config.headers.serialize) {
      config.data = serialize(config.data);
      delete config.data.serialize;
    }

    // 处理get 请求的数组 springmvc 可以处理
    if (config.method === "get") {
      config.paramsSerializer = function(params) {
        return qs.stringify(params, { arrayFormat: "repeat" });
      };
    }

    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// HTTP response拦截
axios.interceptors.response.use(
  res => {
    NProgress.done();
    const status = Number(res.status) || 200;
    const message = res.data.msg || errorCode[status] || errorCode["default"];

    // 后台定义 401 针对令牌过去的特殊响应码
    if (status===424||(status === 401 && (res.data.code===10412))) {
      toLogin();
      return;
    }

    if (status !== 200 || res.data.code === 1) {
      Message({
        message: message,
        type: "error"
      });
      return Promise.reject(new Error(message));
    }
    if (status===200 && res.data.code!==undefined && res.data.code!==200){
      Message({
        message: message,
        type: "error"
      });
      return Promise.reject(new Error(message));
    }
    return res;
  },
  error => {
    NProgress.done();
    return Promise.reject(new Error(error));
  }
);


function out() {
  store.dispatch("LogOut").then(() => {
    // 刷新登录页面，避免多次弹框
    window.location.reload();
  });
}

function startCountDown() {
  if (countDown > 0) {
    setTimeout(() => {
      countDown--;
      updateButtonText();
      startCountDown();
    }, 1000);
  }else {
    out()
  }
}

function updateButtonText() {
  document.getElementById('timed').innerHTML = countDown;
}

function toLogin() {
  startCountDown(); // 启动倒计时
  MessageBox.alert(`令牌状态已过期，请您重新登录；<span id=\'timed\' style=\'color: #06B7AE\'>10</span>s秒自动进入登录页` , '系统提示', {
    confirmButtonText: '重新登录',
    type: 'warning',
    dangerouslyUseHTMLString: true,
    showClose:false
  }).then(()=>{
    out()
  });
}

export default axios;
